package com.ruoyi.common.minio.configuration;


import com.ruoyi.common.core.redis.RedisCache;
import io.minio.BucketExistsArgs;
import io.minio.MakeBucketArgs;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import io.minio.errors.*;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.time.LocalDate;

/**
 * Minio配置类
 * @author jinyao
 */
@Component
@RequiredArgsConstructor
public class MinioConfig implements InitializingBean {

    @Value("${minio.bucket}")
    private String bucket;

    @Value("${minio.host}")
    private String host;

    @Value("${minio.url}")
    private String url;

    @Value("${minio.access-key}")
    private String accessKey;

    @Value("${minio.secret-key}")
    private String secretKey;

    private MinioClient minioClient;

    private final RedisCache redisCache;



    @Override
    public void afterPropertiesSet() {
        Assert.hasText(url, "Minio url is required");
        Assert.hasText(accessKey, "Minio accessKey is required");
        Assert.hasText(secretKey, "Minio secretKey is required");
        this.minioClient = MinioClient.builder().endpoint(this.host).credentials(this.accessKey, this.secretKey).build();
    }

    public String putObject(MultipartFile multipartFile) throws ServerException, InsufficientDataException, ErrorResponseException, IOException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException, XmlParserException, InternalException {
        // bucket 不存在 创建
        if (!minioClient.bucketExists(BucketExistsArgs.builder().bucket(this.bucket).build())){
            minioClient.makeBucket(MakeBucketArgs.builder().bucket(this.bucket).build());
        }
        String objectName;
        try(InputStream inputStream = multipartFile.getInputStream()){
            // 上传文件的名称
            String filename = multipartFile.getOriginalFilename();
            LocalDate localDate = LocalDate.now();
            Long minioCount = redisCache.incr("minio_count", 1);
            objectName = localDate+ "/" + minioCount + "/" + filename;
            // 上传文件
            minioClient.putObject(PutObjectArgs.builder()
                    .bucket(this.bucket)
                    .contentType(multipartFile.getContentType())
                    .object(objectName).stream(inputStream, inputStream.available(), -1).build());
        }
        return this.url + "/" + this.bucket + "/" + objectName;
    }
}

